
const app = getApp<IAppOption>()
Date.prototype.format = function(format) {
  /*
   * eg:format="YYYY-MM-dd hh:mm:ss";

   */
  var o = {
      "M+" :this.getMonth() + 1, // month
      "d+" :this.getDate(), // day
      "h+" :this.getHours(), // hour
      "m+" :this.getMinutes(), // minute
      "s+" :this.getSeconds(), // second
      "q+" :Math.floor((this.getMonth() + 3) / 3), // quarter
      "S" :this.getMilliseconds()
  // millisecond
  }
  if (/(y+)/.test(format)) {
      format = format.replace(RegExp.$1, (this.getFullYear() + "")
              .substr(4 - RegExp.$1.length));
  }
  for ( var k in o) {
      if (new RegExp("(" + k + ")").test(format)) {
          format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k]
                  : ("00" + o[k]).substr(("" + o[k]).length));
      }
  }
  return format;
}

class TApi{
  constructor(){
    this.config ={
      apiUrl:"https://ai.seedlight.cn:31000/foo/seedlight/commonapp", 
      devControlUrl:"https://ai.seedlight.cn:31000/foo/seedlight/",
      deviceApi:"https://ai.seedlight.cn:31000/foo/seedlight/getAppAllRealData"
    };
    this.userInfo={};
  };
  callApi(apiCode , apiPs){
    var me = this;
    return new Promise((success, faild)=>{
      try {
        var psData = apiPs||{};
        psData.code = apiCode;
        wx.request({
          method:"POST",
          url:me.config.apiUrl,
          data:psData,
          complete:(res)=>{
            var result = (res && res.data && res.data.body)?res.data.body:null;
            success(result);
          }
        })
      } catch (error) {
        console.log('call api error', error);
      }
    })
  };
  callDeviceApi(apiCode , apiPs){
    var me = this;
    return new Promise((success, faild)=>{
      try {
        var psData = apiPs||{};
        psData.code = apiCode;
        wx.request({
          method:"POST",
          url:me.config.devControlUrl+apiCode,
          data:psData,
          complete:(res)=>{
            var result = (res && res.data && res.data.body)?res.data.body:null;
            success(result);
          }
        })
      } catch (error) {
        console.log('call api error', error);
      }
    })
  };
  getDeviceInfo(snCode){
    var me = this;
    return new Promise((success, faild)=>{
      try {
        var psData = {
          snCode:snCode
        }
        wx.request({
          method:"POST",
          url:me.config.devControlUrl+'getRealData',
          data:psData,
          complete:(res)=>{
            var result = (res && res.data && res.data.body)?res.data.body:null;
            var dev = result!=null?result[0]:{};
            try {
              if( dev.status){
                dev.online= dev.status=='on'?'在线':'离线'
              }
              dev.led= dev.light>0?'开':'关';
              dev.v = parseFloat(0.001 * dev.volt).toFixed(3);
              dev.i = parseFloat(0.001 * dev.cur).toFixed(3);
              if( dev.imageUrl &&  dev.imageUrl.length>0 && dev.imageUrl.indexOf("_")>0 && dev.imageUrl.indexOf(".jpg")>0 ){
                var t0 = dev.imageUrl.split('_')[1];
                var t = 1000.0* parseInt(t0.split(".")[0]);
                var dt = new Date(t);
                dev.photoTm = dt.format("yyyy-MM-dd hh:mm:ss");
              }
            } catch (error1) {
              console.log(error1)
            }
            success(dev);
          }
        })
      } catch (error) {
        console.log('call api error', error);
      }
    })
  };
  getDeviceSplit(snCode){
    var me = this;
    return new Promise((success, faild)=>{
      var splits =[];
      try {
        var psData = {
          snCode:snCode
        }
        me.callDeviceApi('getPlanList', psData).then(res=>{
          console.log('split' , res);
          for( var i=0;i<24;i++){
            var flag = res.filter( r=>{
              var t = i*3600;
              return t>=r.start && t<r.start+r.len;
            }).length>0;
            var item = {
              t:i ,
              f:flag,
              caption:i<10?'0'+i.toString()+":00" : i.toString()+":00" 
            }
            splits.push(item);
          } 
          success(splits)
        })
      } catch (error) {
        console.log('call api error', error);
        success(splits)
      }
    })
  };
  setDeviceSplit(snCode , splits){
    var me = this;
    return new Promise((success, faild)=>{
      try {
        var psData = {
          snCode:snCode,
          plan:splits
        }
        me.callDeviceApi('setPlanList', psData).then(res=>{
          console.log(res);
        })
      } catch (error) {
        console.log('call api error', error);
      }
    })
  };
};

var api = new TApi();
export{
  api
}